package video.web;
/*
 */
import util.GetHtml;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * url example http://v.youku.com/v_show/id_XNDIxNjA5OTYw.html
 * @author ladjzero
 *
 */
public class Youku extends SuperParser{
	private boolean hasJson = false;
	
	private String jUrl;
	private JSONObject jo;
	private JSONObject jData;
	
	public Youku(String videoUrl){
		super(videoUrl);
	}
	
	public boolean isReachable(){
		if( null == content)
			return false;
		else
			return true;
	}
	
	public String getFileUrl(){
		if( !hasJson )
			getJson();
		return "http://f.youku.com/player/getFlvPath/sid/00_00/st/flv/fileid/"+
				getFileID(jData.getJSONObject("streamfileids").getString("flv"), jData.getDouble("seed"))+
				"?K="+
				JSONObject.fromObject(jData.getJSONObject("segs").getJSONArray("flv").get(0)).getString("k");
	}
	
	public String getImage(){
		if( !hasJson )
			getJson();
		JSONArray ja = JSONArray.fromObject( jo.getString("data") );
		if(0==ja.size())	//null
			return null;
		JSONObject jo2 = JSONObject.fromObject(ja.getString(0));
		return jo2.getString("logo");
	}
	
	public String getSwf(){
		return "http://player.youku.com/player.php/sid/"+vid+"/v.swf";
	}
	
	private void getJson(){
		jUrl = "http://v.youku.com/player/getPlayList/VideoIDS/"+vid;
		String receive = new GetHtml().get( jUrl );
		jo = JSONObject.fromObject( receive );
		jData = JSONObject.fromObject( JSONArray.fromObject( jo.getString("data")).get(0) );
		
		hasJson = true;
	}
	
	/*
	 * @author http://3shi.net/
	 */
	private String getFileID(String fileid, double seed) {
		String mixed = getFileIDMixString(seed);
		String[] ids = fileid.split("\\*");
		StringBuilder realId = new StringBuilder();
		int idx;
		for (int i = 0; i < ids.length; i++) {
			idx = Integer.parseInt(ids[i]);
			realId.append(mixed.charAt(idx));
		}
		return realId.toString();
	}

	private String getFileIDMixString(double seed) {
		StringBuilder mixed = new StringBuilder();
		StringBuilder source = new StringBuilder(
				"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\\:._-1234567890");
		int index, len = source.length();
		for (int i = 0; i < len; ++i) {
			seed = (seed * 211 + 30031) % 65536;
			index = (int) Math.floor(seed / 65536 * source.length());
			mixed.append(source.charAt(index));
			source.deleteCharAt(index);
		}
			return mixed.toString();
	}	
}
